package com.mingmen.supplier.activity;


import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.imagepicker.ui.ImagePreviewDelActivity;
import com.lzy.imagepicker.view.CropImageView;
import com.mingmen.supplier.R;
import com.mingmen.supplier.adapter.CommodityManagerAdapter;
import com.mingmen.supplier.adapter.CreateLabelAdapter;
import com.mingmen.supplier.adapter.ImagePickerAdapter;
import com.mingmen.supplier.adapter.MyLabelAdapter;
import com.mingmen.supplier.base.BaseBean;

import com.mingmen.supplier.definerecycleview.SwipeRecyclerView;
import com.mingmen.supplier.defineview.ClearEditText;
import com.mingmen.supplier.defineview.GlideRoundTransform;
import com.mingmen.supplier.dialog.ButtomDialogView;
import com.mingmen.supplier.http.MyOkhttp;
import com.mingmen.supplier.http.callback.StringCallback;
import com.mingmen.supplier.httpconfig.AppConfig;
import com.mingmen.supplier.httpconfig.HttpResponse;
import com.mingmen.supplier.imageloader.GlideImageLoader;
import com.mingmen.supplier.immersionbar.ImmersionBar;
import com.mingmen.supplier.label.bean.LabelTestBean;
import com.mingmen.supplier.model.PicSendModel;
import com.mingmen.supplier.model.SpecModel;
import com.mingmen.supplier.util.GsonUtil;
import com.mingmen.supplier.util.MyStringUtils;
import com.mingmen.supplier.util.SharePreferenceUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;
import okhttp3.Call;
import okhttp3.Response;

public class CreateCommodityActivity extends AppCompatActivity implements CreateLabelAdapter.OnItemClickListener, ImagePickerAdapter.OnRecyclerViewItemClickListener {

    //返回按钮
    @BindView(R.id.text_return)
    TextView textReturn;

    CreateLabelAdapter myLabelAdapter;
    private int maxImgCount = 8;               //允许选择图片最大数
    List<SpecModel.DataBean> dataList = new ArrayList<>();
    @BindView(R.id.recycle_list)
    SwipeRecyclerView recycle_list;
    @BindView(R.id.btn_login)
    Button btn_login;

    String token;
    @BindView(R.id.edit_CommidyName)
    ClearEditText edit_CommidyName;
    @BindView(R.id.edit_describe)
    EditText edit_describe;
    @BindView(R.id.edit_Specs)
    EditText edit_Specs;


    ArrayList<ImageItem> images = new ArrayList<>();
    private ArrayList<ImageItem> selImageList = new ArrayList<>(); //当前选择的所有图片
    public static final int IMAGE_ITEM_ADD = -1;
    public static final int REQUEST_CODE_SELECT = 100;
    public static final int REQUEST_CODE_PREVIEW = 101;
    @BindView(R.id.img_shopTu)
    ImageView img_shopTu;
    private ImagePicker imagePicker;
    @BindView(R.id.linear_return)
    LinearLayout linear_return;
    ButtomDialogView bottomSheetDialog;

    GridLayoutManager gridLayoutManager1;
    private ImagePickerAdapter adapter;
    @BindView(R.id.check_yue)
    CheckBox check_yue;
    String specAccuracy = "0";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_createcommodity);
        ButterKnife.bind(this);
        ImmersionBar.with(this)
                .statusBarDarkFont(true, 0.2f)
                .init();
        EventBus.getDefault().register(this);
        token = (String) SharePreferenceUtil.get(this, "token", "");
        gridLayoutManager1 = new GridLayoutManager(this, 3);

        adapter = new ImagePickerAdapter(this, selImageList, maxImgCount);
        adapter.setOnItemClickListener(this);
        imageCreate();


        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 3);
        recycle_list.setLayoutManager(gridLayoutManager);
        myLabelAdapter = new CreateLabelAdapter(this);

        recycle_list.setAdapter(myLabelAdapter);
        DividerItemDecoration divider = new DividerItemDecoration(this, DividerItemDecoration.VERTICAL);
        divider.setDrawable(ContextCompat.getDrawable(this, R.drawable.custom_divider));
        recycle_list.addItemDecoration(divider);
        HttpResponse.getSpecByUser(token, "3", new StringCallback(this) {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                Log.d("getSpecByUser", s);
                SpecModel specModel = new SpecModel();
                specModel = GsonUtil.GsonToBean(s, SpecModel.class);
                dataList.addAll(specModel.getData());
                myLabelAdapter.setDataList(dataList);
            }
        });

        myLabelAdapter.setOnItemClickListener(new CreateLabelAdapter.OnItemClickListener() {
            @Override
            public void onItemClickListener(View view, int pos, List<SpecModel.DataBean> myLiveList) {
                myLabelAdapter.setCheckedPosition(pos);
                edit_Specs.setText(myLiveList.get(pos).getName());
            }
        });
        imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new GlideImageLoader());
        imagePicker.setMultiMode(true);
        imagePicker.setShowCamera(true);
        imagePicker.setCrop(false);
        imagePicker.setSaveRectangle(true);
        imagePicker.setStyle(CropImageView.Style.RECTANGLE);
        Integer width = Integer.valueOf(280);
        Integer height = Integer.valueOf(280);
        width = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, width, getResources().getDisplayMetrics());
        height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, height, getResources().getDisplayMetrics());
        imagePicker.setFocusWidth(width);
        imagePicker.setFocusHeight(height);
        imagePicker.setOutPutX(Integer.valueOf(800));
        imagePicker.setOutPutY(Integer.valueOf(800));
        check_yue.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    edit_Specs.setText("500g");
                    specAccuracy = "1";
                } else {
                    edit_Specs.setText("");
                    specAccuracy = "0";
                }
            }
        });
    }

    Intent intent;

    @OnClick({R.id.text_return, R.id.btn_login, R.id.img_shopTu, R.id.linear_return})
    public void onViewClicked(View view) {

        switch (view.getId()) {
            case R.id.text_return:
            case R.id.linear_return:
                finish();
                break;
            case R.id.btn_login:
                if (TextUtils.isEmpty(edit_CommidyName.getText().toString())) {
                    Toast.makeText(this, "请输入商品名称", Toast.LENGTH_SHORT).show();
                } else if (TextUtils.isEmpty(edit_describe.getText().toString())) {
                    Toast.makeText(this, "请输入商品描述", Toast.LENGTH_SHORT).show();
                } else if (TextUtils.isEmpty(edit_Specs.getText().toString())) {
                    Toast.makeText(this, "请输入商品规格", Toast.LENGTH_SHORT).show();
                } else {
//                    String path_img= MyStringUtils.returnStringBuffer(pictureList);

                    HttpResponse.createCommodity(token, edit_CommidyName.getText().toString(), path, edit_describe.getText().toString(), edit_Specs.getText().toString(), "101", specAccuracy, new StringCallback(this) {
                        @Override
                        public void onSuccess(String s, Call call, Response response) {
                            Log.d("createCommodity", "createCommodity");
                            BaseBean baseBean = new BaseBean();
                            baseBean = GsonUtil.GsonToBean(s, BaseBean.class);
                            if (baseBean.getCode() == 0) {
                                EventBus.getDefault().post(19);
                                startActivity(new Intent(CreateCommodityActivity.this,AuditListActivity.class));
                                finish();
                            }
                            Toast.makeText(CreateCommodityActivity.this, baseBean.getMessage() + "", Toast.LENGTH_SHORT).show();
                        }
                    });
                }

                break;
            case R.id.img_shopTu:

                LayoutInflater layoutInflater = LayoutInflater.from(CreateCommodityActivity.this);
                View view1 = layoutInflater.inflate(R.layout.dialog_bottom_send, null);

                bottomSheetDialog = new ButtomDialogView(CreateCommodityActivity.this, view1, true, true);
//                bottomSheetDialog.setContentView(R.layout.toast_dialog);
                bottomSheetDialog.show();

                TextView text_dismiss = view1.findViewById(R.id.text_dismiss);
                text_dismiss.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        bottomSheetDialog.dismiss();
                    }
                });

                ImageView img_camera = view1.findViewById(R.id.img_camera);
                img_camera.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent1 = new Intent(CreateCommodityActivity.this, ImageGridActivity.class);
                        intent1.putExtra(ImageGridActivity.EXTRAS_TAKE_PICKERS, true); // 是否是直接打开相机
                        startActivityForResult(intent1, REQUEST_CODE_SELECT);
                        bottomSheetDialog.dismiss();
                    }
                });
                ImageView img_calumb = view1.findViewById(R.id.img_calumb);
                img_calumb.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        intent = new Intent(CreateCommodityActivity.this, ImageGridActivity.class);
                        intent.putExtra(ImageGridActivity.EXTRAS_IMAGES, images);
                        //ImagePicker.getInstance().setSelectedImages(images);
                        startActivityForResult(intent, 100);
                        bottomSheetDialog.dismiss();
                    }
                });
                break;
        }
    }

    List<File> myfile = new ArrayList<>();
    String path;
    File file;
    List<String> pictureList = new ArrayList<>();

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (myfile.size() > 0) {
            myfile.clear();
        }
        if (images.size() > 0) {
            images.clear();
        }
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            //添加图片返回
            if (data != null && requestCode == REQUEST_CODE_SELECT) {
                images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                for (int i = 0; i < images.size(); i++) {
                    Log.d("dkdkdkk", images.get(i).path);
                    path = images.get(i).path;
                    file = new File(path);
                    myfile.add(file);
                }
//                MyOkhttp.post("http://192.168.3.18:9001/system/upload/img")
                MyOkhttp.post(AppConfig.IMGURL+"/system/upload/img")
                        .params("token", "123")
                        .addFileParams("file", myfile)
                        .execute(new StringCallback(this) {
                            @Override
                            public void onSuccess(String s, Call call, Response response) {
                                Log.d("DKkdkdkd", s);
                                BaseBean baseBean = new BaseBean();
                                baseBean = GsonUtil.GsonToBean(s, BaseBean.class);
                                if (baseBean.getCode() == 0) {
                                    PicSendModel picSendModel = new PicSendModel();
                                    picSendModel = GsonUtil.GsonToBean(s, PicSendModel.class);
//                                    img_shopTu
//                                    placeholder(R.mipmap.zhanwei).error(R.mipmap.zhanwei).
                                    Glide.with(CreateCommodityActivity.this).load(AppConfig.IMGURL + picSendModel.getData().get(0)).dontAnimate().transform(new GlideRoundTransform(CreateCommodityActivity.this, 5)).into(img_shopTu);
                                } else {
                                    img_shopTu.setImageResource(R.mipmap.img_add);
                                }

                                myfile.clear();
                            }
                        });
         /*       Bitmap bm = BitmapFactory.decodeFile(images.get(0).path);
                img_shopTu.setImageBitmap(bm);*/
            }


        } else if (resultCode == ImagePicker.RESULT_CODE_BACK) {
            //预览图片返回
            if (data != null && requestCode == REQUEST_CODE_PREVIEW) {
                images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_IMAGE_ITEMS);
                if (images != null) {
                    selImageList.clear();
                    selImageList.addAll(images);
                }
            }
        }
    }


    @Override
    public void onItemClickListener(View view, int pos, List<SpecModel.DataBean> myLiveList) {

    }

    @Override
    public void onItemClick(View view, int position) {
        switch (view.getId()) {
            case R.id.img_cel:
                selImageList.remove(position);
                adapter.setImages(selImageList);
                adapter.notifyDataSetChanged();
                break;
            case R.id.iv_img:
                switch (position) {
                    case IMAGE_ITEM_ADD:
                        ImagePicker.getInstance().setSelectLimit(maxImgCount - selImageList.size());
                        Intent intent1 = new Intent(CreateCommodityActivity.this, ImageGridActivity.class);

//                                intent1.putExtra(ImageGridActivity.EXTRAS_IMAGES,images);
                        startActivityForResult(intent1, REQUEST_CODE_SELECT);
                        break;
                    default:
                        //打开预览
                        Intent intentPreview = new Intent(this, ImagePreviewDelActivity.class);
                        intentPreview.putExtra(ImagePicker.EXTRA_IMAGE_ITEMS, (ArrayList<ImageItem>) adapter.getImages());
                        intentPreview.putExtra(ImagePicker.EXTRA_SELECTED_IMAGE_POSITION, position);
                        intentPreview.putExtra(ImagePicker.EXTRA_FROM_ITEMS, true);
                        startActivityForResult(intentPreview, REQUEST_CODE_PREVIEW);
                        break;
                }

                break;

        }
    }

    public void imageCreate() {
        imagePicker = ImagePicker.getInstance();

        imagePicker.setImageLoader(new GlideImageLoader());
        imagePicker.setMultiMode(true);
        imagePicker.setShowCamera(true);
        imagePicker.setCrop(false);
        imagePicker.setSaveRectangle(true);
        imagePicker.setStyle(CropImageView.Style.RECTANGLE);
        Integer width = Integer.valueOf(280);
        Integer height = Integer.valueOf(280);
        width = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, width, getResources().getDisplayMetrics());
        height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, height, getResources().getDisplayMetrics());
        imagePicker.setFocusWidth(width);
        imagePicker.setFocusHeight(height);
        imagePicker.setOutPutX(Integer.valueOf(800));
        imagePicker.setOutPutY(Integer.valueOf(800));
    }
    public void onEventMainThread(Integer integer) {


    }
}




